During the summer of 2012, wild fires ravaged throughout the Algerian territory covering most of the northern part, especially the coastal cities. This disaster was due to the higher than average temperatures which reached as high as 50 degrees Celcius.
One important measure against the reproduction of such disasters is the ability to predict their occurrence. Moreover, in this project, we will attempt to predict these forest fires based on multiple features related to weather indices.
The Dataset we will use to train and test our models consists of 244 observations on two Algerian Wilayas (cities): Sidi-Bel Abbes and Bejaia. The observations have been gathered throughout the duration of 4 months from June to September 2012 for both cities.
The Dataset contains the following variables:
We first start off by importing the necessary libraries for our analysis.
The libraries we used are the following:
The Dataset provided to us was in the form of a .csv file that contained two tables, one table for the observations belonging to the Sidi-Bel Abbes region, and the other for Bejaia.
Before starting our analysis we separated the tables into two distinct files according to the region. We named both files Algerian_forest_fires_dataset_Bejaia.csv and Algerian_forest_fires_dataset_Sidi_Bel_Abbes.csv for Bejaia and Sidi-Bel Abbes respectively.
We first check the existence of null values in the Dataset, none were found.
colSums(is.na(df_s))
day month year Temperature RH Ws
0 0 0 0 0 0
Rain FFMC DMC DC ISI BUI
0 0 0 0 0 0
FWI Classes
0 0
We then process to add a column in both datasets to indicate the region(Wilaya) in each table. We chose the following encoding:
df_b[["Region"]] = 0
df_s[["Region"]] = 1
After that, we proceed to merge both our datasets into one single dataframe using full_join(), this will allow us to easily explore and analyze the data.
str(df)
'data.frame': 244 obs. of 15 variables:
$ day : int 1 2 3 4 5 6 7 8 9 10 ...
$ month : int 6 6 6 6 6 6 6 6 6 6 ...
$ year : int 2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 ...
$ Temperature: int 32 30 29 30 32 35 35 28 27 30 ...
$ RH : int 71 73 80 64 60 54 44 51 59 41 ...
$ Ws : int 12 13 14 14 14 11 17 17 18 15 ...
$ Rain : num 0.7 4 2 0 0.2 0.1 0.2 1.3 0.1 0 ...
$ FFMC : num 57.1 55.7 48.7 79.4 77.1 83.7 85.6 71.4 78.1 89.4 ...
$ DMC : num 2.5 2.7 2.2 5.2 6 8.4 9.9 7.7 8.5 13.3 ...
$ DC : num 8.2 7.8 7.6 15.4 17.6 26.3 28.9 7.4 14.7 22.5 ...
$ ISI : num 0.6 0.6 0.3 2.2 1.8 3.1 5.4 1.5 2.4 8.4 ...
$ BUI : num 2.8 2.9 2.6 5.6 6.5 9.3 10.7 7.3 8.3 13.1 ...
$ FWI : num 0.2 0.2 0.1 1 0.9 3.1 6 0.8 1.9 10 ...
$ Classes : chr "not fire " "not fire " "not fire " "not fire " ...
$ Region : num 1 1 1 1 1 1 1 1 1 1 ...
unique(df$month)
[1] 6 7 8 9
We check again for any NA values that might have been introduced into the dataset by merging the data from both tables, we found out there was one row that contained NA value in DC and FWI. We delete that row since it will not affect our overall dataset.
dim(df)
[1] 243 15
We now proceed to display the different range of values some categorical variables might contain, mainly the Classes and the Region columns.
unique(df$Region)
[1] 1 0
We find that the Classes column has values that contain unneeded space characters, we proceed to trim those spaces.
df$Classes <- trimws(df$Classes, which = c("both"))
unique(df$Classes)
[1] "not fire" "fire"
We then turn the fire/not fire values into 1/0 respectively for future analysis.
df$Classes <- mapvalues(df$Classes, from=c("not fire","fire"), to=c(0,1))
The following `from` values were not present in `x`: not fire, fire
str(df)
'data.frame': 243 obs. of 15 variables:
$ day : int 1 2 3 4 5 6 7 8 9 10 ...
$ month : int 6 6 6 6 6 6 6 6 6 6 ...
$ year : int 2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 ...
$ Temperature: int 32 30 29 30 32 35 35 28 27 30 ...
$ RH : int 71 73 80 64 60 54 44 51 59 41 ...
$ Ws : int 12 13 14 14 14 11 17 17 18 15 ...
$ Rain : num 0.7 4 2 0 0.2 0.1 0.2 1.3 0.1 0 ...
$ FFMC : num 57.1 55.7 48.7 79.4 77.1 83.7 85.6 71.4 78.1 89.4 ...
$ DMC : num 2.5 2.7 2.2 5.2 6 8.4 9.9 7.7 8.5 13.3 ...
$ DC : num 8.2 7.8 7.6 15.4 17.6 26.3 28.9 7.4 14.7 22.5 ...
$ ISI : num 0.6 0.6 0.3 2.2 1.8 3.1 5.4 1.5 2.4 8.4 ...
$ BUI : num 2.8 2.9 2.6 5.6 6.5 9.3 10.7 7.3 8.3 13.1 ...
$ FWI : num 0.2 0.2 0.1 1 0.9 3.1 6 0.8 1.9 10 ...
$ Classes : num 0 0 0 0 0 1 1 0 0 1 ...
$ Region : num 1 1 1 1 1 1 1 1 1 1 ...
We delete the year column since all obserations were performed in the same year
str(df_scaled)
'data.frame': 243 obs. of 14 variables:
$ day : int 1 2 3 4 5 6 7 8 9 10 ...
$ month : int 6 6 6 6 6 6 6 6 6 6 ...
$ Temperature: num -0.042 -0.593 -0.869 -0.593 -0.042 ...
$ RH : num 0.604 0.739 1.211 0.132 -0.138 ...
$ Ws : num -1.243 -0.887 -0.531 -0.531 -0.531 ...
$ Rain : num -0.0314 1.6159 0.6175 -0.3809 -0.281 ...
$ FFMC : num -1.4455 -1.5431 -2.0309 0.1085 -0.0517 ...
$ DMC : num -0.983 -0.967 -1.007 -0.765 -0.7 ...
$ DC : num -0.865 -0.873 -0.878 -0.714 -0.668 ...
$ ISI : num -0.997 -0.997 -1.069 -0.612 -0.708 ...
$ BUI : num -0.976 -0.969 -0.99 -0.779 -0.716 ...
$ FWI : num -0.919 -0.919 -0.932 -0.811 -0.825 ...
$ Classes : num 0 0 0 0 0 1 1 0 0 1 ...
$ Region : num 1 1 1 1 1 1 1 1 1 1 ...
We have ended up with a clean and scaled dataframe named df_scaled, which we will use to visualize and further explore our data.
Our first instinct is to compare the two regions together in terms of number of fires, and average temperature.
We used the unscaled dataset to plot the real life values of the temperatures.
df %>%
group_by(Region) %>%
summarise(Region = Region, Number_of_fires = sum(Classes), Temperature = mean(Temperature)) %>%
ggplot(aes(x=Region, y=Number_of_fires, fill = Temperature))+
geom_col(position='dodge')
`summarise()` has grouped output by 'Region'. You can override using the `.groups` argument.
We can see that the the Sidi-Bel Abbes region has in total a greater number of fires and a higher average temperature throughout the summer of 2012.
The previous results push us to suspect a positive relationship between the temperature and the likelihood of having a fire. However, we need to investigate all the other variables, which is why we will plot a correlation matrix of the features in the dataset.
We performed feature selection using the Caret package to determine which features are the most important and which are the least.
In this case, we opted for Linear Discriminant Analysis with Stepwise Feature Selection by specifying stepLDA as our method.
The varImp function returns a measure of importance out of 100 for each of the features. According to the official Caret documentation, the importance metric is calculated by conducting a ROC curve analysis on each predictor; a series of cutoffs is applied to the predictor data to predict the class. The AUC is then computed and is used as a measure of variable importance.
We can see that the variables month, Ws, Region, and day are insignificant compared to other features. We will disregard them in our model. To determine this we used a threshold of 0.7 for the importance measure.
For the following models, we will only use the features that were the most significant in our feature selection phase. The selected features are:
We begin by splitting the data into train/test sets with a 80/20 split. This split was chosen by default as a good practice. This will leave us with 191 observations in the training set as well as 52 in the test set. Due to the small nature of the dataset at hand we will later apply cross validation to some models in order to further examine their performance and compare them with each other.
We set a seed of 1000
dim(test_set)
[1] 52 14
Logistic Regression is considered to be an extension of Linear Regression, in which we predict the qualitative response for an observation. It gives us the probability of a certain observation belonging to a class in binomial classification, but can also be extended to be used for multiple classifications.
We first start by fitting our model on the training set. As we do that we get an error that our model did not converge, this is due to our model being able to perfectly split the dataset into positive/negative observations. This might soud counterintuitive but this error is a good sign.
logistic_model <- glm(Classes ~ Temperature+Rain+FFMC+DMC+DC+ISI+BUI+FWI+RH, data=train_set, family="binomial")
Warning: glm.fit: algorithm did not convergeWarning: glm.fit: fitted probabilities numerically 0 or 1 occurred
logistic_model <- glm(Classes ~ Temperature+Rain+FFMC+DMC+DC+ISI+BUI+FWI+RH, data=train_set, family="binomial")
Warning: glm.fit: algorithm did not convergeWarning: glm.fit: fitted probabilities numerically 0 or 1 occurred
logistic_model
Call: glm(formula = Classes ~ Temperature + Rain + FFMC + DMC + DC +
ISI + BUI + FWI + RH, family = "binomial", data = train_set)
Coefficients:
(Intercept) Temperature Rain FFMC DMC DC
195.74 -42.31 50.32 114.50 -57.81 65.45
ISI BUI FWI RH
301.95 -38.43 155.10 -17.28
Degrees of Freedom: 190 Total (i.e. Null); 181 Residual
Null Deviance: 261.5
Residual Deviance: 1.428e-07 AIC: 20
Since logistic regression gives us the probability of each observation belonging to the 1 class, we will use a 0.5 threshold to transform that probability into a classification of either 0 or 1.
After getting our predictions, we will use the confusion matrix function from the caret library that computes a set of performance matrices including f1-score, recall and precision. Other matrices computed include: sensitivity, specificity, prevalence etc. The official documentation for this function and the formulas for all matrices are found in this link. We will only be interested in the f1-score, recall, precision, accuracy and balanced accuracy.
Our model gives us an accuracy and an f1 score of 100% on the training set.
confusionMatrix(preds_logistic, train_set$Classes,
mode = "everything",
positive="1")
Confusion Matrix and Statistics
Reference
Prediction 0 1
0 83 0
1 0 108
Accuracy : 1
95% CI : (0.9809, 1)
No Information Rate : 0.5654
P-Value [Acc > NIR] : < 2.2e-16
Kappa : 1
Mcnemar's Test P-Value : NA
Sensitivity : 1.0000
Specificity : 1.0000
Pos Pred Value : 1.0000
Neg Pred Value : 1.0000
Precision : 1.0000
Recall : 1.0000
F1 : 1.0000
Prevalence : 0.5654
Detection Rate : 0.5654
Detection Prevalence : 0.5654
Balanced Accuracy : 1.0000
'Positive' Class : 1
On the test set hovewer, we get an accuracy of 98.08% and an f1 score of 98.25%.
confusionMatrix(preds_logistic, test_set$Classes,
mode = "everything",
positive="1")
Confusion Matrix and Statistics
Reference
Prediction 0 1
0 23 1
1 0 28
Accuracy : 0.9808
95% CI : (0.8974, 0.9995)
No Information Rate : 0.5577
P-Value [Acc > NIR] : 2.743e-12
Kappa : 0.9612
Mcnemar's Test P-Value : 1
Sensitivity : 0.9655
Specificity : 1.0000
Pos Pred Value : 1.0000
Neg Pred Value : 0.9583
Precision : 1.0000
Recall : 0.9655
F1 : 0.9825
Prevalence : 0.5577
Detection Rate : 0.5385
Detection Prevalence : 0.5385
Balanced Accuracy : 0.9828
'Positive' Class : 1
As we plot the ROC curve, we can see that the AUC is equal to 98.27586% which is almost a perfect classifier.
auc
[1] 0.9610195
Linear Discriminant Analysis is best used when the decision boundary of our given dataset is assumed to be linear. There are two basic assumptions that LDA takes into consideration:
Since LDA assumes that each input variable has the same variance, we will use the standardized data-frame in the train test splits. Each variable in the standardized data-frame has mean of 0 and variance of 1.
lda_model
Call:
lda(Classes ~ Temperature + Rain + FFMC + DMC + DC + ISI + BUI +
FWI + RH, data = train_set, family = "binomial")
Prior probabilities of groups:
0 1
0.434555 0.565445
Group means:
Temperature Rain FFMC DMC DC ISI
0 -0.6330807 0.3721387 -0.8343419 -0.6612676 -0.5799594 -0.8280654
1 0.4633549 -0.3244797 0.6739891 0.4867494 0.4267318 0.6591273
BUI FWI RH
0 -0.6669278 -0.8161663 0.4701120
1 0.4850895 0.6262935 -0.3699445
Coefficients of linear discriminants:
LD1
Temperature 0.08978603
Rain 0.18218660
FFMC 1.35842928
DMC -1.15810129
DC -0.32744874
ISI 0.37584652
BUI 1.09904453
FWI 0.92679809
RH 0.57487142
On our training data, the model reached an accuracy of 95.81% and an f1 score of 96.30%, with 4 false positives and 1 false negative.
confusionMatrix(preds_lda$class, train_set$Classes,
mode = "everything",
positive="1")
Confusion Matrix and Statistics
Reference
Prediction 0 1
0 79 4
1 4 104
Accuracy : 0.9581
95% CI : (0.9191, 0.9817)
No Information Rate : 0.5654
P-Value [Acc > NIR] : <2e-16
Kappa : 0.9148
Mcnemar's Test P-Value : 1
Sensitivity : 0.9630
Specificity : 0.9518
Pos Pred Value : 0.9630
Neg Pred Value : 0.9518
Precision : 0.9630
Recall : 0.9630
F1 : 0.9630
Prevalence : 0.5654
Detection Rate : 0.5445
Detection Prevalence : 0.5654
Balanced Accuracy : 0.9574
'Positive' Class : 1
As we can see below, our the number of false positives is 1, and the number of false negatives is 1 as well. Our model also yielded an accuracy of 96.15% and an f1 score of 96.55%.
confusionMatrix(preds_lda$class, test_set$Classes,
mode = "everything",
positive="1")
Confusion Matrix and Statistics
Reference
Prediction 0 1
0 22 1
1 1 28
Accuracy : 0.9615
95% CI : (0.8679, 0.9953)
No Information Rate : 0.5577
P-Value [Acc > NIR] : 5.691e-11
Kappa : 0.922
Mcnemar's Test P-Value : 1
Sensitivity : 0.9655
Specificity : 0.9565
Pos Pred Value : 0.9655
Neg Pred Value : 0.9565
Precision : 0.9655
Recall : 0.9655
F1 : 0.9655
Prevalence : 0.5577
Detection Rate : 0.5385
Detection Prevalence : 0.5577
Balanced Accuracy : 0.9610
'Positive' Class : 1
The AUC for LDA was 96.10%, similar to the one for Logistic Regression.
Quadratic Discriminant Analysis is best used when the decision boundary of our given dataset is assumed to be non-linear. Similarly to LDA, QDA makes two basic assumptions:
qda_model
Call:
qda(Classes ~ Temperature + Rain + FFMC + DMC + DC + ISI + BUI +
FWI + RH, data = train_set)
Prior probabilities of groups:
0 1
0.4764398 0.5235602
Group means:
Temperature Rain FFMC DMC DC
0 -0.5780859 0.4348542 -0.8150123 -0.6690568 -0.6056867
1 0.4762177 -0.3204676 0.6659827 0.6215861 0.5279307
ISI BUI FWI RH
0 -0.8222968 -0.6779796 -0.8138050 0.4522544
1 0.6175900 0.6185834 0.6580962 -0.3615521
[Interpretation on the coefficients]
Our model yields an accuracy of 98.95% and an f1 score of 99.07% on the training set.
confusionMatrix(preds_qda$class, train_set$Classes,
mode = "everything",
positive="1")
Confusion Matrix and Statistics
Reference
Prediction 0 1
0 82 1
1 1 107
Accuracy : 0.9895
95% CI : (0.9627, 0.9987)
No Information Rate : 0.5654
P-Value [Acc > NIR] : <2e-16
Kappa : 0.9787
Mcnemar's Test P-Value : 1
Sensitivity : 0.9907
Specificity : 0.9880
Pos Pred Value : 0.9907
Neg Pred Value : 0.9880
Precision : 0.9907
Recall : 0.9907
F1 : 0.9907
Prevalence : 0.5654
Detection Rate : 0.5602
Detection Prevalence : 0.5654
Balanced Accuracy : 0.9893
'Positive' Class : 1
As we can see below, our the number of false positives is 1, and the number of false negatives is 1. The results are very good but the other way around would have been better as we do not want to miss any positives meaning we want to predict all fires. Our model yielded an f1-score of 93.33% and an accuracy of 92.31%.
confusionMatrix(preds_qda$class, test_set$Classes,
mode = "everything",
positive="1")
Confusion Matrix and Statistics
Reference
Prediction 0 1
0 20 1
1 3 28
Accuracy : 0.9231
95% CI : (0.8146, 0.9786)
No Information Rate : 0.5577
P-Value [Acc > NIR] : 7.729e-09
Kappa : 0.8427
Mcnemar's Test P-Value : 0.6171
Sensitivity : 0.9655
Specificity : 0.8696
Pos Pred Value : 0.9032
Neg Pred Value : 0.9524
Precision : 0.9032
Recall : 0.9655
F1 : 0.9333
Prevalence : 0.5577
Detection Rate : 0.5385
Detection Prevalence : 0.5962
Balanced Accuracy : 0.9175
'Positive' Class : 1
After plotting the ROC curve we got an AUC of 91.75%, which is worse than both logistic regression and LDA.
auc
[1] 0.9175412
We can observe that QDA performs better than LDA on the training data, because it has the tendency to over-fit it. However, LDA performs better on the testing data since it generalizes better on unseen data points.
In this section, we will explore KNN’s performance on our problem. We will use hyper parameter tuning to determine the best number of nearest numbers (K) and we will also use repeated cross validation in our training for better performance estimation.
Since KNN is a distance based model, we will here again use our normalized dataset instead of the original.
The summaryFunction argument determines which metric to use to determine the performance of a particular hyperparameter setting. Here we shall use defaultSummary which calculates accuracy and kappa statistic.
We have opted to go with the repeated 10 fold cross-validation method repeated 10 times. ClassProbs parameter is set to TRUE and we can set the threshold later when we test our model performance.
Now we use the train() function to perform the model training/tuning of the k hyper-parameter. The range of k is from 3 to 85 in steps of 2 meaning we will only have odd values of k only as it is best practice for the KNN clustering.
Another tweak that we need to make on our data-set is to change our target variable values to valid R variable names in order for the KNN algorithm to work with class Probabilities as each values of our target variable will become a variable with its own probability values. Leaving the values as {0,1} will throw an error at us, therefore we will set our Classes variable values back to ‘Fire’ and ‘Not_Fire’ and proceed.
```{r}
Error: attempt to use zero-length variable name
Inspecting the probabilities reveals that a cutoff probability around 0.5 give good classification results.
preds = predict(knn_cv,train_set, type = "prob")
train_set %>%
ggplot() +
aes(x = preds$fire, fill = Classes) +
geom_histogram(bins = 20) +
labs(x = "Probability", y = "Count", title = "Distribution of predicted probabilities for value fire" )
pROC_train <- roc(response = train_set$Classes, predictor = preds[,"fire"],
quiet = TRUE,
plot = TRUE,
percent = TRUE,
auc.polygon = TRUE,
print.auc = TRUE,
print.thres = TRUE,
print.thres.best.method = "youden")
preds = predict(knn_cv,test_set, type="raw")
confusionMatrix(preds, test_set$Classes,
mode = "everything",
positive="fire")
preds <- as.vector(preds, mode = "numeric")
test_set$Classes <- as.vector(test_set$Classes, mode = "numeric")
pred <- prediction(preds, test_set$Classes)
perf <- performance(pred,"tpr","fpr")
plot(perf,colorize=TRUE)
The goal of ensemble modeling is to improve performance over a baseline model by combining multiple models. So, we will set the baseline performance measure by starting with one algorithm. In our case, we will build a simple decision tree.
Decision trees are widely used classifiers in industries based on their transparency in describing rules that lead to a prediction. They are arranged in a hierarchical tree-like structure and are simple to understand and interpret. They are not susceptible to outliers and are able to capture nonlinear relationships.
We will be using the rpart library for creating decision trees. rpart stands for recursive partitioning and employs the CART (classification and regression trees) algorithm. Apart from the rpart library, there are many other decision tree libraries like C50, Party, Tree, and mapTree.
Starting with splitting our data into a train and test sets with a train test ratio of 0.8:0.2
set.seed(8)
split <- sample.split(df_scaled, SplitRatio=0.8)
train_set <- subset(df_scaled, split == "TRUE")
test_set <- subset(df_scaled, split=="FALSE")
dim(train_set)
dim(test_set)
Next, we create a decision tree model by calling the rpart function. Let’s first create a base model with default parameters and value. Notice that we do not include any train control meaning that we are not using any bagging, cross validation or pruning techniques. The resulting tree is a simple decision tree. We will explore the performance of the model on the train and test sets next.
base_model <- rpart(Classes ~ Temperature+Rain+FFMC+DMC+DC+ISI+BUI+FWI+RH, data = train_set, method = "class")
summary(base_model)
#Plot Decision Tree
rpart.plot(base_model)
After exploring the confusion matrix and the different performance metrics, we can see that our base decision tree does not fit the data perfectly and has 3 misclassifications on the training set. Those 3 false positives caused the model’s accuracy to be 98% and the f1-score to be 98% as well.
preds = predict(base_model,train_set, type="class")
confusionMatrix(preds, train_set$Classes,
mode = "everything",
positive='1')
Our base decision tree performs very well on unseen data with just one false positive, an accuracy of 98% and an f1-score of 98%.
preds = predict(base_model,test_set, type="class")
confusionMatrix(preds, test_set$Classes,
mode = "everything",
positive='1')
preds <- as.vector(preds, mode = "numeric")
temp_test_set.classes <- as.vector(test_set$Classes, mode = "numeric")
pred <- prediction(preds, temp_test_set.classes)
perf <- performance(pred,"tpr","fpr")
plot(perf,colorize=TRUE)
Prepruning is also known as early stopping criteria. As the name suggests, the criteria are set as parameter values while building the rpart model. Below are some of the pre-pruning criteria that can be used. The tree stops growing when it meets any of these pre-pruning criteria, or it discovers the pure classes.
The complexity parameter (cp) in rpart is the minimum improvement in the model needed at each node. Itís based on the cost complexity of the model and works as follows:
The cp value is a stopping parameter. It helps speed up the search for splits because it can identify splits that donít meet this criteria and prune them before going too far.
Other parameters include but are not limited to:
maxdepth: This parameter is used to set the maximum depth of a tree. In this prepruning step.
minsplit: It is the minimum number of records that must exist in a node for a split to happen or be attempted.
And one last thing, since we are in a classification setting, we have to specify class as the method used for building our tree instead of ‘anova’ that is used in regression settings.
pruned_base_model <- rpart(Classes ~ Temperature+Rain+FFMC+DMC+DC+ISI+BUI+FWI+RH, data = train_set, method = "class", control = rpart.control(cp = 0, maxdepth = 8, minsplit = 8))
summary(pruned_base_model)
#Plot Decision Tree
rpart.plot(pruned_base_model)
The summary of our base model will give us the details of each split with the number of observations, the value of the complexity parameter, the predicted class, the class counts with their probabilities and the children of the node. It will also give details about the future splits starting with the primary splits that will follow and the percent improvement in the prediction as well as the surrogate splits that come later on.
The resulting tree as explained in the above section, is the smallest tree with the lowest miss-classification loss. This tree is plotted with the split details and leaf node classes.
The optimal CP value found was 0.96341463.
preds = predict(pruned_base_model,train_set, type="class")
confusionMatrix(preds, train_set$Classes,
mode = "everything",
positive='1')
The train accuracy of our tree is 99% with an F1 score of 99% as well with a total of 2 misclassifications, 1 FP and 1 FN.
We have a 100% accuracy on our held-out validation set which means we have successfully avoided overfitting using tree pruning.
preds = predict(pruned_base_model,test_set, type="class")
confusionMatrix(preds, test_set$Classes,
mode = "everything",
positive='1')
preds <- as.vector(preds, mode = "numeric")
test_set$Classes <- as.vector(test_set$Classes, mode = "numeric")
pred <- prediction(preds, test_set$Classes)
perf <- performance(pred,"tpr","fpr")
plot(perf,colorize=TRUE)
Bagging, or bootstrap aggregation, is an ensemble method that involves training the same algorithm many times by using different subsets sampled from the training data. The final output prediction is then averaged across the predictions of all the sub-models. The two most popular bagging ensemble techniques are Bagged Decision Trees and Random Forest.
Splitting the dataset
Starting with splitting our data into a train and test sets with a train test ratio of 0.8:0.2
set.seed(8)
split <- sample.split(df_scaled, SplitRatio=0.8)
train_set <- subset(df_scaled, split == "TRUE")
test_set <- subset(df_scaled, split=="FALSE")
dim(train_set)
dim(test_set)
This method performs best with algorithms that have high variance. The argument method=“treebag” specifies the algorithm. We will train our model using a 5-fold cross validation repeated 5 times. The sampling strategy used for the bagged trees is ROSE.
control <- trainControl(method="repeatedcv", number=5, repeats=5)
bagCART_model <- train(Classes ~ Temperature+Rain+FFMC+DMC+DC+ISI+BUI+FWI+RH, data=train_set, method="treebag", metric="Accuracy", trControl=control)
We achieved a perfect fit using bagged trees trained using a 5-fold CV repeated 5 times.
preds = predict(bagCART_model,train_set, type="raw")
confusionMatrix(preds, train_set$Classes,
mode = "everything",
positive='1')
The bagged model did not achieve a perfect performance on unseen data which leads us to believe it over fit the data. This can be caused by the fact that the bagged trees were highly correlated between each other which could be due to the absence of randomization in the features used for each bagged tree. What happenned most probably is the use of the same strong predictors in all bagged trees causing this high correlation between them. In order to get rid of it we will implement Random Forests next which adds this randomization in the features selected for each bagged tree.
preds = predict(bagCART_model,test_set, type="raw")
confusionMatrix(preds, test_set$Classes,
mode = "everything",
positive='1')
Random Forest is an extension of bagged decision trees, where in addition to sampling the data, we also sample the variables in each bagged decision tree. The trees are constructed with the objective of reducing the correlation between the individual decision trees by making sure we do not use the same strong predictors in all bagged trees resulting in strongly correlated trees.
control <- trainControl(method="repeatedcv", number=5, repeats=5)
rf_model <- train(Classes ~ Temperature+Rain+FFMC+DMC+DC+ISI+BUI+FWI+RH, data=train_set, method="rf", metric="Accuracy", trControl=control)
Once again, our randomForest model achieved a perfect fir with a 5-fold CV repeated 5 times.
preds = predict(rf_model,train_set, type="raw")
confusionMatrix(preds, train_set$Classes,
mode = "everything",
positive='1')
We have a slight improvement over the bagged model as now we have only one misclassification with a 985 accuracy. This proves that adding randomization to the features selected for each tree decorrelated them yielding more generalizaiton and better performance on unseen data.
preds = predict(rf_model,test_set, type="raw")
confusionMatrix(preds, test_set$Classes,
mode = "everything",
positive='1')
In boosting, multiple models are trained sequentially and each model learns from the errors of its predecessors. We will use the Stochastic Gradient Boosting algorithm.
An important thing to note is that sochastic gradient boosting takes a much longer time to train as it is a step-wise method which takes a lot of iterations to converge. Adding cross-validation makes it even longer.
99.48% accuracy on training data with 1 false positive. No noticeable improvement over random forests.
preds = predict(SGB,train_set, type="raw")
confusionMatrix(preds, train_set$Classes,
mode = "everything",
positive='1')
98.08% accuracy on unseen data, same as the training set, boosting did not bring much over our random forest model and considering the very high training time, it is unnecessary to use this method on our problem.
preds = predict(SGB,test_set, type="raw")
confusionMatrix(preds, test_set$Classes,
mode = "everything",
positive='1')
Support Vector Machine is a discriminative classifier that classifies obserations using a hyperplane that best differentiates between the classes. Its advantages lay in the fact that they are very flexible and work well on high-dimensional data.
We will use SVM on our dataset to demonstrate its capabilities.
The goal of the SVM is to identify a boundary that minimizes the total distance between the hyper-plane and the closest points on each class.
There are two hyper-parameters to take into consideration before training our SVM model: first, the cost C which acts as a regularization parameter and trades off correct classifications of the training examples against the maximization of the decision boundary. In other words, the greater the value of C the higher the number of errors occurring in the training classifications. The second hyper-parameter gamma defines how much curvature we want in our decision boundary.
We start by tuning our model according to different values of gamma and C. We will start by using a linear kernel.
To use the cross validation functions from the Caret package, we need to turn the 0/1 categorical values of the variable Classes into “fire”/“not_fire” (as required). The functions provided will allow us to find the best values for both gamma and C. we used a tuning length of 10.
unique(train_set$Classes)
[1] not_fire fire
Levels: not_fire fire
We perform repeated cross validation with
svm_model_linear
Support Vector Machines with Linear Kernel
191 samples
9 predictor
2 classes: 'not_fire', 'fire'
No pre-processing
Resampling: Cross-Validated (10 fold, repeated 5 times)
Summary of sample sizes: 172, 172, 171, 172, 172, 172, ...
Resampling results:
ROC Sens Spec
0.9982444 0.98 0.952
Tuning parameter 'C' was held constant at a value of 1
As we can see above, the best values were found to be sigma = 0.2510562 and C = 16 for the radial kernel, and C = 1 for the linear kernel.
Using the radial kernel resulted in an AUC of 99% while the linear gave us an AUC of 99.8%.
NOTE: Even though the seed is set at 6, the values for C and sigma might change when trying to reproduce the experiment due to the dataset being small nd relatively non-complex. Still, the values for the AUC and accuracy will be still very high.
We will then proceed to show the confusion matrix of the model.
confusionMatrix(preds_svm_train_linear,train_set$Classes, positive="fire")
Confusion Matrix and Statistics
Reference
Prediction not_fire fire
not_fire 91 2
fire 0 98
Accuracy : 0.9895
95% CI : (0.9627, 0.9987)
No Information Rate : 0.5236
P-Value [Acc > NIR] : <2e-16
Kappa : 0.979
Mcnemar's Test P-Value : 0.4795
Sensitivity : 0.9800
Specificity : 1.0000
Pos Pred Value : 1.0000
Neg Pred Value : 0.9785
Prevalence : 0.5236
Detection Rate : 0.5131
Detection Prevalence : 0.5131
Balanced Accuracy : 0.9900
'Positive' Class : fire
For the radial kernel: our model gave us an accuracy of 100% on the training set and 96.15% on the test set.
For the linear kernel: the model gave an accuracy of 98.95% on the train set and performed worse than the radial kernel, which is expected since it is less flexible and fits the data less well. On the test set however, it gave us the same accuracy.
Overall, since our focus would be to correctly classify fires, we will go with the radial kernel since it gave us a fewer number of false negatives than the linear one.
We get an AUC value of 0.953 using the SVM classifier.